﻿# videolog.py
import pymysql
import os
import json
from datetime import datetime
from pydantic import BaseModel, Field, validator

# ===================== 数据库配置 =====================
DB_CONFIG = {
    "host": "localhost",
    "user": "root",
    "password": "wozui666",
    "database": "mydb",
    "charset": "utf8mb4"
}

LOG_DIR = "logs"
os.makedirs(LOG_DIR, exist_ok=True)


# ===================== 数据模型（对应 viewlogs 表） =====================
class ViewLog(BaseModel):
    video_id: str = Field(..., description="视频ID，唯一标识一个视频")
    user_id: str = Field(..., description="用户ID，唯一标识一个用户")
    user_sex: int =Field(0,description="用户性别，1为男0为女")
    play_time: datetime = Field(..., description="视频播放时间，精确到毫秒")
    play_duration: float = Field(..., description="视频播放时长（秒），保留1位小数")
    user_follow: int = Field(0, description="是否关注主播：1=已关注，0=未关注")
    user_like: int = Field(0, description="用户是否喜欢：0=未操作，1=点击喜欢，2=取消喜欢")
    user_comment: str | None = Field("", description="用户评论内容")
    user_gift: float = Field(-1.0, description="打赏礼物价值，未打赏为-1")
    total_likes: int = Field(0, description="视频总喜欢数量")
    total_comments: int = Field(0, description="视频总评论数量")
    total_gifts: int = Field(0, description="视频总礼物数量")

    # 自动确保 play_duration 保留1位小数
    @validator("play_duration", pre=True)
    def round_duration(cls, v):
        return round(float(v), 1)


# ===================== 写日志 =====================
def write_log(viewlog: ViewLog):
    """写日志到文件"""
    today = datetime.now().strftime("%Y-%m-%d")
    log_file = os.path.join(LOG_DIR, f"api_calls_{today}.log")

    params = viewlog.model_dump()

    # 转换 datetime 为字符串
    for k, v in params.items():
        if isinstance(v, datetime):
            params[k] = v.strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]

    log_entry = {
        "time": datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3],
        "params": params
    }

    with open(log_file, "a", encoding="utf-8") as f:
        f.write(json.dumps(log_entry, ensure_ascii=False) + "\n")



# ===================== 插入或更新记录 =====================
def insert_or_update_viewlog(viewlog: ViewLog):
    """
    插入或更新视频观看日志。
    如果同一用户对同一视频已有记录，则更新相关字段。
    """
    print("🚀 调用 insert_or_update_viewlog 成功")

    conn = pymysql.connect(**DB_CONFIG)
    cursor = conn.cursor()
    try:
        sql = """
        INSERT INTO viewlogs (
            video_id, user_id, user_sex,play_time, play_duration,
            user_follow, user_like, user_comment, user_gift,
            total_likes, total_comments, total_gifts
        ) VALUES (
            %(video_id)s, %(user_id)s,%(user_sex)s, %(play_time)s, %(play_duration)s,
            %(user_follow)s, %(user_like)s, %(user_comment)s, %(user_gift)s,
            %(total_likes)s, %(total_comments)s, %(total_gifts)s
        )
        ON DUPLICATE KEY UPDATE
            user_sex= VALUES(user_sex),
            play_time = VALUES(play_time),
            play_duration = VALUES(play_duration),
            user_follow = VALUES(user_follow),
            user_like = VALUES(user_like),
            user_comment = VALUES(user_comment),
            user_gift = VALUES(user_gift),
            total_likes = VALUES(total_likes),
            total_comments = VALUES(total_comments),
            total_gifts = VALUES(total_gifts)
        """
        cursor.execute(sql, viewlog.model_dump())
        conn.commit()
        return True, "✅ 数据插入或更新成功"
    except Exception as e:
        conn.rollback()
        return False, f"❌ 数据库错误: {e}"
    finally:
        cursor.close()
        conn.close()


